import Popup from './popup'

function setEntityStyle(entity, material) {
    if(entity.position) {
        if(entity.point) entity.point.color = material
        if(entity.billboard) entity.billboard.color = material
    } else if(entity.polygon) {
        entity.polygon.material = material
    } else if(entity.polyline) {
        entity.polyline.material = material
    }
}

function onEntityClickEvent(viewer) {
    const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
    let popup = null, entity = null, material = null
    handler.setInputAction(function (movement) {
        if(popup) popup.close()
        if(entity) setEntityStyle(entity, material)
        const pick = viewer.scene.pick(movement.position);
        if (Cesium.defined(pick)) {
            entity = pick.id
            const attr = entity.properties ? entity.properties.getValue(Date.now()) : {}
            let center = null
            if(entity.position) {
                center = entity.position.getValue(Date.now())
                if(entity.point) material = entity.point.color
                if(entity.billboard) material = entity.billboard.material
            } else if(entity.polygon) {
                const polyPositions = entity.polygon.hierarchy.getValue(Date.now()).positions;
                const polyCenter = Cesium.BoundingSphere.fromPoints(polyPositions).center;
                center = Cesium.Ellipsoid.WGS84.scaleToGeodeticSurface(polyCenter)
                material = entity.polygon.material
            } else if(entity.polyline) {
                const polyPositions = entity.polyline.positions.getValue(Date.now());
                const polyCenter = Cesium.BoundingSphere.fromPoints(polyPositions).center;
                center = Cesium.Ellipsoid.WGS84.scaleToGeodeticSurface(polyCenter)
                material = entity.polyline.material
            }

            setEntityStyle(entity, Cesium.Color.fromCssColorString('#0ff').withAlpha(1))

            popup = new Popup({
                viewer: viewer,
                geometry: center,
                title: attr.name || attr['NAME'] || 'title',
                content: attr.remark || attr.name || attr['NAME'] || 'content'
            })
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
}

export {
    onEntityClickEvent
}
